package com.ruoyi.system.service.impl;

import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import com.ruoyi.common.enums.ProjectStatus;
import com.ruoyi.common.enums.TaskType;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.domain.vo.SysWhitePaperSurveyResultVo;
import com.ruoyi.system.domain.vo.SysWhitePaperTaskVo;
import com.ruoyi.system.event.WhitePaperSurveyTaskEvent;
import com.ruoyi.system.service.ISysWhitePaperOutlineService;
import com.ruoyi.system.service.ISysWhitePaperProjectService;
import com.ruoyi.system.service.ISysWhitePaperSurveyResultService;
import com.ruoyi.system.utils.InstructionUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.compress.utils.Lists;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.SysWhitePaperSurveyTaskMapper;
import com.ruoyi.system.service.ISysWhitePaperSurveyTaskService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 白皮书调研任务Service业务层处理
 *
 * @author ruoyi
 * @date 2025-10-20
 */
@Service
public class SysWhitePaperSurveyTaskServiceImpl implements ISysWhitePaperSurveyTaskService
{
    @Autowired
    private SysWhitePaperSurveyTaskMapper sysWhitePaperSurveyTaskMapper;
    @Autowired
    private ISysWhitePaperSurveyResultService sysWhitePaperSurveyResultService;
    @Autowired
    private ISysWhitePaperOutlineService sysWhitePaperOutlineService;
    @Autowired
    private ISysWhitePaperProjectService sysWhitePaperProjectService;
    @Autowired
    private ApplicationEventPublisher eventPublisher;

    /**
     * 查询白皮书调研任务
     *
     * @param id 白皮书调研任务主键
     * @return 白皮书调研任务
     */
    @Override
    public SysWhitePaperSurveyTask selectSysWhitePaperSurveyTaskById(Long id)
    {
        return sysWhitePaperSurveyTaskMapper.selectSysWhitePaperSurveyTaskById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void startTask(Long projectId) {
        // 根据项目ID查询任务列表
        List<SysWhitePaperSurveyTask> whitePaperSurveyTaskList = sysWhitePaperSurveyTaskMapper.listSurveyTaskByProjectId(projectId);

        // 根据项目ID更新任务状态为执行中
        SysWhitePaperSurveyTask sysWhitePaperSurveyTask = new SysWhitePaperSurveyTask();
        sysWhitePaperSurveyTask.setProjectId(projectId);
        sysWhitePaperSurveyTask.setStatus(ProjectStatus.RUN.getCode());
        sysWhitePaperSurveyTask.setUpdateBy(SecurityUtils.getUsername());
        sysWhitePaperSurveyTask.setUpdateTime(DateUtils.getNowDate());
        sysWhitePaperSurveyTaskMapper.updateSurveyTaskByProjectId(sysWhitePaperSurveyTask);

        // 更新项目状态为执行中
        SysWhitePaperProject sysWhitePaperProject = new SysWhitePaperProject();
        sysWhitePaperProject.setId(projectId);
        sysWhitePaperProject.setProjectStatus(ProjectStatus.RUN.getCode());
        sysWhitePaperProjectService.updateSysWhitePaperProject(sysWhitePaperProject);

        // 发布异步处理调研任务事件
        eventPublisher.publishEvent(new WhitePaperSurveyTaskEvent(this,whitePaperSurveyTaskList));
    }

    /**
     * 查询白皮书调研任务列表
     *
     * @return 白皮书调研任务
     */
    @Override
    public List<SysWhitePaperTaskVo> selectSysWhitePaperSurveyTaskList(Long projectId)
    {
        // 根据项目ID查询调研任务列表
        List<SysWhitePaperTaskVo> whitePaperTaskList = sysWhitePaperSurveyTaskMapper.selectSysWhitePaperSurveyTaskList(projectId);

        if (CollectionUtils.isNotEmpty(whitePaperTaskList)) {
           // 根据项目ID按任务ID统计调研结果数量
           List<SysWhitePaperSurveyResultVo> surveyResultVoList = sysWhitePaperSurveyResultService.countSurveyResultByProjectId(projectId);

           if (CollectionUtils.isNotEmpty(surveyResultVoList)) {
               // 循环遍历匹配调研结果数量
               for (SysWhitePaperTaskVo whitePaperTask:whitePaperTaskList) {
                   for (SysWhitePaperSurveyResultVo surveyResultVo:surveyResultVoList) {
                       if (whitePaperTask.getId().equals(surveyResultVo.getTaskId())) {
                           whitePaperTask.setSurveyResultNum(surveyResultVo.getSurveyResultNum());
                       }
                   }
               }
           }
        }

        return whitePaperTaskList;
    }

    /**
     * 新增白皮书调研任务
     *
     * @param sysWhitePaperSurveyTask 白皮书调研任务
     * @return 结果
     */
    @Override
    public int insertSysWhitePaperSurveyTask(SysWhitePaperSurveyTask sysWhitePaperSurveyTask)
    {
        sysWhitePaperSurveyTask.setCreateTime(DateUtils.getNowDate());
        return sysWhitePaperSurveyTaskMapper.insertSysWhitePaperSurveyTask(sysWhitePaperSurveyTask);
    }

    /**
     * 修改白皮书调研任务
     *
     * @param sysWhitePaperSurveyTask 白皮书调研任务
     * @return 结果
     */
    @Override
    public int updateSysWhitePaperSurveyTask(SysWhitePaperSurveyTask sysWhitePaperSurveyTask)
    {
        sysWhitePaperSurveyTask.setUpdateTime(DateUtils.getNowDate());
        return sysWhitePaperSurveyTaskMapper.updateSysWhitePaperSurveyTask(sysWhitePaperSurveyTask);
    }

    /**
     * 批量删除白皮书调研任务
     *
     * @param ids 需要删除的白皮书调研任务主键
     * @return 结果
     */
    @Override
    public int deleteSysWhitePaperSurveyTaskByIds(Long[] ids)
    {
        return sysWhitePaperSurveyTaskMapper.deleteSysWhitePaperSurveyTaskByIds(ids);
    }

    /**
     * 删除白皮书调研任务信息
     *
     * @param id 白皮书调研任务主键
     * @return 结果
     */
    @Override
    public int deleteSysWhitePaperSurveyTaskById(Long id)
    {
        return sysWhitePaperSurveyTaskMapper.deleteSysWhitePaperSurveyTaskById(id);
    }

    @Override
    public void batchInsertSysWhitePaperSurveyTask(SysWhitePaperRequire whitePaperRequire, List<SysWhitePaperOutline> outlineList, String chapterName, String loginUserName, Date currentDate) {
        for (SysWhitePaperOutline outline:outlineList) {
            SysWhitePaperOutline.DataSourceInfo dataSourceInfo = outline.getDataSourceInfo();
            // 1,AI生成任务
            List<SysWhitePaperKnowledgeBase> knowledgeBaseList = dataSourceInfo.getKnowledgeBaseList();
            String knowledgeBaseStr = null;
            if (CollectionUtils.isNotEmpty(knowledgeBaseList)) {
                List<String> fileNameList = knowledgeBaseList.stream().map(knowledge -> knowledge.getOriginFileName()).collect(Collectors.toList());

                knowledgeBaseStr = String.join(",",fileNameList);
            }
            // 指令词
            String instructionWorkflow = InstructionUtils.generateInsturction(whitePaperRequire.getIndustry(),whitePaperRequire.getSurveyIndustryKeynote(),chapterName,outline.getTitle(),knowledgeBaseStr,outline.getCollectionRequirements());

            SysWhitePaperSurveyTask whitePaperSurveyTask = new SysWhitePaperSurveyTask();
            whitePaperSurveyTask.setProjectId(outline.getProjectId());
            whitePaperSurveyTask.setOutlineId(outline.getId());
            whitePaperSurveyTask.setTaskName(chapterName + "-" + outline.getTitle() + "AI调研任务");
            whitePaperSurveyTask.setInstructionWorkflow(instructionWorkflow);
            whitePaperSurveyTask.setStatus(ProjectStatus.NOT_BEGIN.getCode());
            whitePaperSurveyTask.setTaskType(TaskType.AI.getCode());
            whitePaperSurveyTask.setCreateBy(loginUserName);
            whitePaperSurveyTask.setCreateTime(currentDate);

            sysWhitePaperSurveyTaskMapper.insertSysWhitePaperSurveyTask(whitePaperSurveyTask);

            // 2,网站爬取任务
            String websites = dataSourceInfo.getWebsites();
            if (StringUtils.isNotEmpty(websites)) {
                String[] websiteArray = websites.split(",");

                for (int i=0;i<websiteArray.length;i++) {
                    String website = websiteArray[i];
                    SysWhitePaperSurveyTask whitePaperSurveyTask2 = new SysWhitePaperSurveyTask();
                    whitePaperSurveyTask2.setProjectId(outline.getProjectId());
                    whitePaperSurveyTask2.setOutlineId(outline.getId());
                    whitePaperSurveyTask2.setTaskName(chapterName + "-" + outline.getTitle() + "网站爬虫任务" + (i+1));
                    whitePaperSurveyTask2.setInstructionWorkflow(website);
                    whitePaperSurveyTask2.setStatus(ProjectStatus.NOT_BEGIN.getCode());
                    whitePaperSurveyTask2.setTaskType(TaskType.WEBSITE.getCode());
                    whitePaperSurveyTask2.setCreateBy(loginUserName);
                    whitePaperSurveyTask2.setCreateTime(currentDate);

                    sysWhitePaperSurveyTaskMapper.insertSysWhitePaperSurveyTask(whitePaperSurveyTask2);
                }
            }
        }

//        sysWhitePaperSurveyTaskMapper.batchInsertSysWhitePaperSurveyTask(whitePaperSurveyTaskList);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateSurveyTaskStatus(List<SysWhitePaperSurveyTask> whitePaperSurveyTaskList) {
        for (SysWhitePaperSurveyTask tempTask:whitePaperSurveyTaskList) {
            Long projectId = tempTask.getProjectId();
            Long taskId = tempTask.getId();
            String surveyResultTitle = tempTask.getSurveyResultTitle();

            // 更新白皮书调研任务状态
            SysWhitePaperSurveyTask whitePaperSurveyTask = new SysWhitePaperSurveyTask();
            whitePaperSurveyTask.setId(taskId);
            whitePaperSurveyTask.setStatus(ProjectStatus.FINISH.getCode());
            sysWhitePaperSurveyTaskMapper.updateSysWhitePaperSurveyTask(whitePaperSurveyTask);

            // 保存调研结果信息
            List<String> surveyResultList = tempTask.getSurveyResultList();
            if (CollectionUtils.isNotEmpty(surveyResultList)) {
                List<SysWhitePaperSurveyResult> whitePaperSurveyResultList = Lists.newArrayList();
                for (String surveyResult:surveyResultList) {
                    SysWhitePaperSurveyResult whitePaperSurveyResult = new SysWhitePaperSurveyResult();
                    whitePaperSurveyResult.setProjectId(projectId);
                    whitePaperSurveyResult.setTaskId(taskId);
                    whitePaperSurveyResult.setSurveyResultTitle(surveyResultTitle);
                    whitePaperSurveyResult.setSurveyResult(surveyResult);

                    whitePaperSurveyResultList.add(whitePaperSurveyResult);
                }
                sysWhitePaperSurveyResultService.batchInsertSysWhitePaperSurveyResult(whitePaperSurveyResultList);

                // 更新大纲的调研分析结果
                SysWhitePaperOutline sysWhitePaperOutline = new SysWhitePaperOutline();
                sysWhitePaperOutline.setId(tempTask.getOutlineId());
                sysWhitePaperOutline.setAiAnalyseResultTitle(surveyResultTitle);
                sysWhitePaperOutline.setAiAnalyseResult(String.join("；",surveyResultList));
                sysWhitePaperOutlineService.updateSysWhitePaperOutline(sysWhitePaperOutline);
            }
        }
    }

    @Override
    public int deleteSysWhitePaperSurveyTaskByProjectId(Long projectId) {
        return sysWhitePaperSurveyTaskMapper.deleteSysWhitePaperSurveyTaskByProjectId(projectId);
    }

    @Override
    public List<SysWhitePaperSurveyTask> listSurveyTaskOfRun() {
        return sysWhitePaperSurveyTaskMapper.listSurveyTaskOfRun();
    }
}
